function $(id){
  return document.getElementById(id);
}

function Base(id){
  this.array = [1,2,3];
  this.id = id;
  this.init();
}
Base.prototype.init = function(){
  if(this.id == 'tag'){
    // tag监听键盘事件
    $('tagVal').addEventListener('keyup',(event)=>{
      console.log(event.keyCode);
      if(event.keyCode == 188 ||  event.keyCode == 229 || event.keyCode == 13  || event.keyCode == 32){
        this.add();
      }
     },false);

    $('tag').addEventListener('mouseover',(e)=>{
       console.log(e.target)
       if(e.target.nodeName.toLowerCase() == 'span'){
          e.target.innerText = '删除' + e.target.innerText;
          e.target.style.background = 'red'; 
       }
    },false);

    $('tag').addEventListener('mouseout',(e)=>{
      console.log(e.target)
      if(e.target.nodeName.toLowerCase() == 'span'){
         e.target.innerText = e.target.innerText.substring(2);
         e.target.style.background = 'blue'; 
      }
   },false);
   $('tag').addEventListener('click',(e)=>{
    console.log(e.target)
    if(e.target.nodeName.toLowerCase() == 'span'){
      let index = this.array.indexOf(e.target.innerText.substring(2));
      this.array.splice(index,1);
      this.render();
    }
 },false);
  }else{
      // 添加兴趣爱好
      $('add').addEventListener('click',()=>{
        this.add();
      },false);
  }
  this.render();
}

Base.prototype.render = function(){
  $(this.id).innerHTML = this.array.map((e)=>{
    let className = 'tag';
    if(this.id == 'hobby'){
      className = 'hobby';
    }
    return `<span class="${className}">${e}</span>`
  }).join('');
}

Base.prototype.add = function(){
  if(this.id == 'tag'){ 

    let val = $('tagVal').value.trim();
    let index = this.array.indexOf(val);
    if(index > 0) return;
    this.array.push(val);
    if(this.array.length>10) this.array.shift();
    $('tagVal').value = '';

  }else{

    let str = $('textArea').value.trim();
    let arrWord = str.split(/[^0-9a-zA-Z\u4e00-\u9fa5]+/).filter(function(e) {
        return e.length>0
    });
    this.array = this.array.concat(arrWord);
    let arr = [];
    for(let i=this.array.length-1;i>-1;i--){
      console.log('132',arr.indexOf(this.array[i]))
      if(arr.indexOf(this.array[i]) == -1){
        arr.push(this.array[i]);
      }
    }
    arr = arr.reverse();
    if(arr.length>10){
      arr = arr.slice(-10);
    }
    this.array = arr;
    $('textArea').value = '';
  }
  this.render();
  
}

let Tag = new Base('tag');
let Hob = new Base('hobby');
// 正则表达是还是不会用，需要加强学习
// slice() 截取 一直都是从前向后，不管开头是几
// revese() 翻转数组
// 数组去重还是有bug 数值得索引不对
// 封装模式完全不理解  
